
package com.idealighter.game.games.errenniuniu.handler;

import com.idealighter.game.core.annotation.ResMsgHandler;
import com.idealighter.game.dictionary.domain.ErrenniuniuRoomDomain;
import com.idealighter.game.dictionary.domain.RobotConfigDomain;
import com.idealighter.game.gamehall.dto.MemInfo;
import com.idealighter.game.games.errenniuniu.ErRenNiuNiuPlayer;
import com.idealighter.game.games.errenniuniu.message.ReqExchangeTableMsg;
import com.idealighter.game.games.errenniuniu.message.ReqReadyMsg;
import com.idealighter.game.message.core.ResMessage;
import com.idealighter.game.robot.core.Player;
import com.idealighter.game.robot.handler.ResMessageHandler;
import com.idealighter.utils.code.RandCodeUtil;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@ResMsgHandler(502230)
public class ResGameOverHandler implements ResMessageHandler {

  private static final Logger LOG = LoggerFactory.getLogger(ResGameOverHandler.class);

  @Override
  public void action(Player player, ResMessage message) {
    MemInfo member = player.member(player.playerId);

    ErrenniuniuRoomDomain roomDomain = ((ErRenNiuNiuPlayer) player).roomDomain;

    // 校验玩家身上的钱换成的筹码是否足够(最小筹码*8 + 台费)
    if (member.getChips() < roomDomain.getMinOne() * 8) {
      LOG.info("[二人牛牛]玩家[{}][{}]身上的筹码小于最小筹码*8", player.userName, player.playerId);
      player.delayLogout();
      return;
    }

    RobotConfigDomain robotCfg = player.configDomain;
    // 超过最大携带金币需要退出房间
    if (convertGold(roomDomain, member.getChips()) > robotCfg.getMaxGold()) {
      LOG.info("[二人牛牛]玩家[{}][{}]身上的金币超过最大携带金币", player.userName, player.playerId,
          robotCfg.getMaxGold());
      player.delayLogout();
      return;
    }

    // 超过最大游戏局数
    if (player.totalGameNum-- < 1) {
      LOG.info("[二人牛牛]玩家[{}][{}]超过总游戏局数退出游戏...", player.userName, player.playerId);
      player.delayLogout();
      return;
    }

    // 超过换桌局数
    if (player.tableGameNum-- < 1) {
      player.tableGameNum =
          RandCodeUtil.random(robotCfg.getTableGameLower(), robotCfg.getTableGameUpper());
      LOG.info("[二人牛牛]玩家[{}][{}]超过换桌局数换桌...", player.userName, player.playerId);
      player.schedule(() -> player.sendMsg(new ReqExchangeTableMsg()), RandCodeUtil.random(3, 5),
          TimeUnit.SECONDS);
      return;
    }

    // 游戏结束后继续准备
    player.schedule(() -> player.sendMsg(new ReqReadyMsg()), RandCodeUtil.random(3, 5),
        TimeUnit.SECONDS);
  }

  /**
   * 筹码换算金币.
   * 
   * @param roomDomain .
   * @param chips .
   */
  public long convertGold(ErrenniuniuRoomDomain roomDomain, long chips) {
    return chips * roomDomain.getProportionGold() / roomDomain.getProportionChips();
  }
}
